package handlers

import (
	"MessageSendService/app/common/enum/channalType"
	"MessageSendService/app/common/log"
	"MessageSendService/app/common/models"
	"MessageSendService/app/common/models/accounts"
	"MessageSendService/app/common/scripts"
	"MessageSendService/app/job/etc"
	"MessageSendService/app/job/internal/service"
	"context"
	"encoding/json"
	"fmt"
	"go.uber.org/zap"
	"strconv"
	"time"
)

type SmsHandler struct {
}

func NewSmsHandler() SmsHandler {
	return SmsHandler{}
}

func (s SmsHandler) DoHandler(ctx context.Context, taskInfo models.TaskInfo) error {
	fmt.Println("短信消息", taskInfo)
	if taskInfo.SendChannel == channalType.Sms {

		//发送短信的逻辑
		fmt.Println("发送短信消息：", taskInfo)
		client := scripts.GetSmsClient(etc.Config.SecretId, etc.Config.SecretKey)

		//获取发送账号 todo 暂时都当做腾信短信使用
		account, err := service.GetAccount(taskInfo.SendAccount)
		if err != nil {
			log.GetLogger().Error("获取发送账号失败", zap.Any("err", err))
			return err
		}
		var tencentAccount accounts.TencentSmsAccount
		err = json.Unmarshal([]byte(account.Config), &tencentAccount)
		if err != nil {
			log.GetLogger().Error("反序列化失败:", zap.Any("err", err))
			return err
		}

		var templateParam []string
		// 晚间消息发送
		if account.ID == 2 {
			templateParam = append(templateParam, strconv.Itoa(time.Now().Hour()-12))
			fmt.Println("晚安消息发送,参数为:", templateParam)
		}
		if account.ID == 3 {
			t1 := time.Now().Year()       //年
			t2 := int(time.Now().Month()) //月
			t3 := time.Now().Day()        //日
			t4 := time.Now().Hour()       //小时
			templateParam = append(templateParam, strconv.Itoa(t1), strconv.Itoa(t2), strconv.Itoa(t3), strconv.Itoa(t4))
			fmt.Println("早安消息发送,参数为:", templateParam)
		}
		response, err := client.SendSmsMessage([]string{"+8618806690739"}, accounts.TencentSmsAccount{
			Url:          "",
			SupplierName: "tencent",
			SmsSdkAppId:  "1400671965",
			SignName:     "荆轲爱学习公众号",
			SupplierId:   1,
			Region:       "ap-shanghai",
			TemplateId:   tencentAccount.TemplateId,
		}, templateParam)
		if err != nil {
			log.GetLogger().Error("发送短信消息失败", zap.Any("err", err))
		}
		log.GetLogger().Info("发送消息成功", zap.Any("response", response))
	}
	return nil
}
